<template>
	<view class="root">
		<scroll-view class="content" scroll-y="true">
			<view class="top-title">
				机构登录
			</view>

			<view class="input-view">
				{{payType === 'redeem'?'登录代码':'优惠代码'}}:<input class="input" @input="codeInput" />
			</view>
			<view class="input-view">
				机构名称:<input class="input" :class="isInput?'input-disabled':''" v-model="areaName" :disabled="isInput" />
			</view>
			<view class="input-view">
				机构电话:<input class="input" :class="isInput?'input-disabled':''" v-model="areaPhone" type="number" :disabled="isInput"/>
			</view>
			<view class="input-view" @click="openAddres">
				所在地区:<view class="input" :class="isInput?'input-disabled':''" style="white-space:nowrap;overflow:hidden;text-overflow:ellipsis">{{areaCodeDesc}}</view>
			</view>
			<view class="input-view">
				详细地址:<input class="input" :class="isInput?'input-disabled':''" v-model="address" placeholder="如街道、小区等" :disabled="isInput"></input>
			</view>
			<view v-if="isInput" class="input-hint">* 机构信息可以前往个人信息中心修改,相关信息会出现在测评报告上</view>
			<view v-if="!isInput" class="input-hint">* 建议您如实填写机构信息，相关信息会出现在测评报告上</view>

			<view class="pay-code-view">
				<view class="pay-code-item-view" @click="payTypeClick(item)" v-for="(item,index) in productList" :key="item.id" >
					<view :class="productId===item.id?'pay-code-item-select':'pay-code-item'">
						<view class="pay-code-item-cover">
							<image :src="item.cover" style="width: 200rpx;height: 160rpx;"></image>
						</view>
						<view class="pay-code-item-content">
							<view class="pay-code-title">{{item.name}}</view>
							<view class="pay-code-money">{{item.priceYuan}}</view>
							<view class="pay-code-desc">{{item.promotion}}</view>
						</view>
					</view>

				</view>

			</view>

		</scroll-view>
		<view class="buy-view">
			<!-- 			<view class="buy-agreement">
						<checkbox-group @change="checkboxChange">
							<checkbox :checked="isAgreement" value="1" color="#FACB2F"></checkbox>
						</checkbox-group>
						<view style="#666666">同意</view>
						<view style="color: #FA4F3A;" @click="agreementClick">《会员服务协议》</view>
					</view> -->
			<view class="pay-price-view">
				<view v-if="payType != 'redeem'" style="display: flex;flex-direction: row;align-items: flex-end;">
					<view class="buy-hint">原价:</view>
					<view class="buy-original-price">¥{{originalPrice}}</view>
				</view>
				<view v-if="payType != 'redeem'" style="display: flex;flex-direction: row;margin-left: 20rpx;align-items: flex-end;">
					<view class="buy-hint">实付金额:</view>
					<view style="font-size: 24rpx;">¥</view>
					<view class="buy-money">{{payPrice}}</view>
				</view>
			</view>
			<view class="buy-botton" @click="payClick">
				{{payType === 'redeem'?'立即登录':'立即支付'}}
			</view>
		</view>
		<simple-address ref="simpleAddress" :pickerValueDefault="cityPickerValueDefault" @onConfirm="onConfirm" themeColor="#007AFF"></simple-address>
		<ws-wx-privacy id="privacy-popup"></ws-wx-privacy>
	</view>
</template>

<script>
	import simpleAddress from '@/components/simple-address/simple-address.vue';
	import utils from '../../utils/utils.js'
	import Constant from '../../common/constant.js'
	export default {
		components: {
			simpleAddress
		},
		data() {
			return {
				cityPickerValueDefault: [0, 0, 1],

				isInput: false,
				productId: 0,
				product: {},
				productList: [],

				phone: '',
				promoCode: '',

				areaName: '',
				areaPhone: '',
				areaCodeDesc: '',
				address: '',

				originalPrice: 0,
				payPrice: 0,

				isAgreement: true,

				payType: 'redeem'
			}
		},
		computed: {

		},

		onLoad(option) {
			console.log(option);
			this.evaluateRecordId = option.evaluateRecordId;
			if (this.payType != 'redeem') {
				this.getProductList();
			}
			this.areaName = getApp().globalData.user.org.name;
			this.areaPhone = getApp().globalData.user.org.contactNumber;
			this.areaCodeDesc = getApp().globalData.user.org.pcaCodeDesc;
			if (utils.isEmpty(this.areaCodeDesc)){
				this.areaCodeDesc = '';
			}

			this.areaCode = getApp().globalData.user.org.pcaCode;
			console.log(this.areaCode);
			if (!utils.isEmpty(this.areaCode)){
				var areaCodeStr = this.areaCode.split(',');
				console.log(this.areaCodeStr);
				this.cityPickerValueDefault = areaCodeStr;
			}
			
			this.address = getApp().globalData.user.org.address;
			
			if (!utils.isEmpty(getApp().globalData.user.org.contactNumber)) {
				this.isInput = true;
			}
			
			uni.requirePrivacyAuthorize({
				success: () => {
					console.log('同意');
					// 用户同意授权
					// 继续小程序逻辑
				},
				fail: () => {
					console.log('拒绝');
					uni.navigateBack()
				}, // 用户拒绝授权
				complete: () => {}
			})
		},

		methods: {
			getProductCocer(index) {
				if (index === 0) {
					return '../../static/pay_product_1.png'
				} else if (index === 1) {
					return '../../static/pay_product_2.png'
				} else {
					return '../../static/pay_product_3.png'
				}
			},

			checkboxChange(e) {
				console.log(e);
				this.isAgreement = !this.isAgreement;
				console.log(this.isAgreement);
			},

			openAddres() {
				if (!this.isInput){
					this.cityPickerValueDefault = [0, 0, 1]
					this.$refs.simpleAddress.open();
				}
			},

			onConfirm(e) {
				console.log(e);
				this.areaCodeDesc = e.label;
				this.areaCode = e.value.toString();
			},

			codeInput(event) {
				this.promoCode = event.detail.value.replace(/^\s+|\s+$/g, "");
				if (this.payType === 'redeem') {
					this.previewRedeemCode();
				} else {
					this.previewPromoCode();
				}
			},

			///支付购买
			payClick() {
				console.log(this.isAgreement)
				if (!this.isAgreement) {
					uni.showToast({
						title: '购买需要先同意会员服务协议',
						icon: 'none',
					})
					return;
				}
				if (this.payType === 'redeem') {
					if (utils.isEmpty(this.promoCode)) {
						uni.showToast({
							title: '请填写登录代码',
							icon: 'none',
						});
						return;
					}
					if (utils.isEmpty(this.productId)) {
						uni.showToast({
							title: '登录代码无效',
							icon: 'none',
						});
						return;
					}
				} else {
					if (utils.isEmpty(this.productId)) {
						uni.showToast({
							title: '请选择产品',
							icon: 'none',
						});
						return;
					}
				}

				if (!this.isInput) {
					if (utils.isEmpty(this.areaName)) {
						uni.showToast({
							title: '请填写园区名称',
							icon: 'none',
						})
						return;
					}
					if (utils.isEmpty(this.areaPhone)) {
						uni.showToast({
							title: '请填写园区电话',
							icon: 'none',
						})
						return;
					}
					var isPhone = utils.checkMobile(this.areaPhone);
					var isTel = utils.checkTel(this.areaPhone);
					if (!isPhone & !isTel) {
						uni.showToast({
							title: '请填写正确的联系方式',
							icon: 'none',
						})
						return;
					}
					if (utils.isEmpty(this.areaCodeDesc)) {
						uni.showToast({
							title: '请填写园区所在地区',
							icon: 'none',
						})
						return;
					}
					if (utils.isEmpty(this.address)) {
						uni.showToast({
							title: '请填写园区详细地址',
							icon: 'none',
						})
						return;
					}
					this.postUserInfo();
				} else {
					if (this.payType === 'redeem') {
						this.doRedeem();
					} else {
						this.order();
					}
				}
			},

			payTypeClick(item) {
				this.productId = item.id;
				this.product = item;
				this.originalPrice = item.priceYuan;
				if (this.promoCode === '') {
					this.payPrice = item.priceYuan;
				} else {
					this.payPrice = '计算中...';
					this.previewPromoCode();
				}
			},

			///计费点
			getProductList() {
				uni.showLoading({})
				this.$http.request({
					method: 'GET',
					url: '/eapi/product/vip/list',
				}).then(res => {
					console.log(res);
					uni.hideLoading();
					if (res.code === '000000') {
						this.productList = res.data;
						this.payTypeClick(this.productList[0]);
					} else {
						uni.showToast({
							title: err,
							icon: 'none'
						});
					}
				}).catch(err => {
					uni.hideLoading();
					uni.showToast({
						title: err,
						icon: 'none'
					});
				})
			},
			///计算金额
			previewPromoCode() {
				this.$http.request({
					method: 'POST',
					url: '/eapi/product/vip/preview_promo_code',
					params: {
						productId: this.product.id,
						promoCode: this.promoCode,
					}
				}).then(res => {
					console.log(res);
					if (res.code === '000000') {
						this.payPrice = res.data.newPrice / 100;
					} else {
						this.payPrice = this.originalPrice;
					}
				}).catch(err => {

				})
			},

			///完善用户信息
			postUserInfo() {
				uni.showLoading({});
				this.$http.request({
					method: 'POST',
					url: '/eapi/profile/userinfo',
					params: {
						areaName: this.areaName,
						areaPhone: this.areaPhone,
						areaCode: this.areaCode,
						areaCodeDesc: this.areaCodeDesc,
						address: this.address,
						realName: '',
					}
				}).then(res => {
					uni.hideLoading()
					console.log(res);
					if (this.payType === 'redeem') {
						this.doRedeem();
					} else {
						this.order();
					}
				}).catch(err => {
					uni.hideLoading()
					uni.showToast({
						title: '提交用户信息失败',
						icon: 'none'
					})
				});
			},

			///下订单
			order() {
				uni.showLoading({})
				this.$http.request({
					method: 'GET',
					url: '/eapi/pay/wx/order',
					params: {
						productId: this.product.id,
						productType: this.product.type,
						promoCode: this.promoCode,
					}
				}).then(res => {
					console.log(res)
					uni.hideLoading()
					if (res.code === '000000') {
						this.requestPayment(res)
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				}).catch(err => {
					uni.hideLoading()
					uni.showToast({
						title: err,
						icon: 'none'
					})
				})
			},

			///弹出支付请求
			requestPayment(res) {
				console.log('requestPayment:' + res)
				var that = this;
				var outTradeNo = res.data.outTradeNo;
				uni.requestPayment({
					provider: 'wxpay',
					orderInfo: outTradeNo,
					timeStamp: res.data.wxPayResult.timeStamp,
					nonceStr: res.data.wxPayResult.nonceStr,
					package: res.data.wxPayResult.packageValue,
					signType: res.data.wxPayResult.signType,
					paySign: res.data.wxPayResult.paySign,
					success: function(res) {
						uni.showLoading({});
						that.checkCount = 4;
						that.orderCheck(outTradeNo);
					},
					fail: function(err) {
						uni.showToast({
							title: err,
							icon: 'none'
						})
					}
				})
			},


			///订单支付检查
			orderCheck(outTradeNo) {
				var that = this;
				if (this.checkCount === 0) {
					this.payRecord();
					return;
				}
				this.checkCount = this.checkCount - 1;
				this.$http.request({
					method: 'GET',
					url: '/eapi/pay/wx/order/check',
					params: {
						outTradeNo: outTradeNo
					}
				}).then(res => {
					console.log('orderCheck');
					console.log(res);
					if (res.code === '000000') {
						///更新用户信息
						uni.$emit('event_get_user')
						if (this.evaluateRecordId === '0') {
							uni.navigateBack({});
						} else {
							this.payRecord();
						}
					} else {
						this.timeoutID = setTimeout(function() {
							that.orderCheck(outTradeNo);
							clearTimeout(that.timeoutID);
						}, 3000);
					}
				}).catch(err => {
					console.log('orderCheck');
					console.log(err);
					this.timeoutID = setTimeout(function() {
						that.orderCheck(outTradeNo);
						clearTimeout(that.timeoutID);
					}, 3000);
				})

			},

			///支付完成后，解锁当前测评
			payRecord() {
				console.log(this.evaluateRecordId)
				uni.showLoading({});
				this.$http.request({
					method: 'POST',
					url: '/eapi/operator/pay_record',
					params: {
						evaluateRecordId: this.evaluateRecordId
					}
				}).then(res => {
					console.log(res);
					uni.hideLoading()
					uni.navigateBack({});
				}).catch(err => {
					console.log(err);
					uni.hideLoading()
					uni.navigateBack({});
				})
			},

			agreementClick() {
				uni.navigateTo({
					url: '/pages-assess/web/web?url=https://oss.tuo51.com/public/pages/vip_license.html'
				})
			},

			///兑换码 商品查询
			previewRedeemCode() {
				this.productId = '';
				this.product = null;
				this.productList = [];
				this.$http.request({
					method: 'POST',
					url: '/eapi/product/preview_redeem_code',
					params: {
						redeemCode: this.promoCode,
					}
				}).then(res => {
					console.log(res);
					if (res.code === '000000') {
						this.productId = res.data.id;
						this.product = res.data;
						this.productList.push(res.data);
					}
				}).catch(err => {

				})
			},

			///兑换码 激活
			doRedeem() {
				uni.showLoading({})
				this.$http.request({
					method: 'GET',
					url: '/eapi/product/redeem',
					params: {
						redeemCode: this.promoCode,
					}
				}).then(res => {
					console.log(res)
					uni.hideLoading()
					if (res.code === '000000') {
						///更新用户信息
						var that = this;
						uni.$emit('event_get_user')
						uni.showModal({
							title: '激活成功',
							content: res.data.comment,
							showCancel: false,
							success: function(res) {
								if (res.confirm) {
									if (that.evaluateRecordId === '0') {
										uni.navigateBack({});
									} else {
										that.payRecord();
									}
								}
							}
						})
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				}).catch(err => {
					uni.hideLoading()
					uni.showToast({
						title: err,
						icon: 'none'
					})
				})
			},
		}
	}
</script>

<style lang="scss">
	.root {
		background-color: #F7F7F7;
		height: 100%;
		width: 100%;
	}

	.top-title {
		width: 100%;
		height: 75px;
		background: linear-gradient(360deg, rgba(250, 231, 177, 1) 0%, rgba(214, 168, 88, 1) 100%);
		opacity: 1;
		border-radius: 4px 4px 0px 0px;
		color: #FFFFFF;
		font-size: 36rpx;
		font-weight: bold;
		display: flex;
		justify-content: center;
		align-items: center;
		margin-top: 20rpx;
		@include pay-top-bg();
	}

	.content {
		background-color: #FFFFFF;
		display: flex;
		flex-direction: column;
		padding-bottom: 120rpx;
	}

	.buy-view {
		position: fixed;
		bottom: 0rpx;
		width: 100%;
		height: 100rpx;

		border: 0px solid rgba(230, 230, 230, 1);
		border-top: 1px solid rgba(230, 230, 230, 1);
		opacity: 1;

		display: flex;
		flex-direction: row;
		align-items: center;
		background-color: #FFFFFF;
	}

	.buy-agreement {
		flex: 1;
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;

		font-size: 30rpx;
	}

	.buy-botton {
		width: 240rpx;
		height: 100rpx;
		background: linear-gradient(180deg, rgba(255, 235, 155, 1) 0%, rgba(229, 187, 79, 1) 100%);
		opacity: 1;

		font-size: 30rpx;
		color: #FFFFFF;
		display: flex;
		justify-content: center;
		align-items: center;
		align-self: flex-end;
		@include pay-buy-btn();
	}

	.buy-hint {
		font-size: 24rpx;
		color: rgba(102, 102, 102, 1);
		opacity: 1;
		margin-right: 10rpx;
		/* background-color: #4CD964; */
	}

	.buy-money {
		font-size: 40rpx;
		color: rgba(255, 151, 10, 1);
		opacity: 1;
		margin-left: 5rpx;
		/* background-color: #007AFF; */
	}

	.buy-original-price {
		font-size: 24rpx;
		color: rgba(51, 51, 51, 1);
		opacity: 1;
		text-decoration: line-through;
	}

	.pay-last-show {
		font-size: 12px;
		font-family: PingFang SC;
		font-weight: 400;
		line-height: 17px;
		color: rgba(170, 170, 170, 1);
		opacity: 1;

		width: 100%;
		text-align: center;

		margin-bottom: 40rpx;
		margin-top: 40rpx;
	}

	.pay-last-show-img {
		width: 10px;
		height: 11px;
		opacity: 1;
		margin-right: 20rpx;
	}

	.input-view {
		display: flex;
		flex-direction: row;
		align-items: center;
		margin-top: 20rpx;
		margin-left: 40rpx;

		font-size: 15px;
		font-family: PingFang SC;
		font-weight: 400;
		line-height: 29px;
		color: rgba(102, 102, 102, 1);
	}

	.input {
		width: 400rpx;
		height: 30px;
		border: 1px solid rgba(221, 221, 221, 1);
		opacity: 1;
		border-radius: 4px;
		margin-left: 10rpx;
		padding-left: 5rpx;
		padding-right: 5rpx;
	}
	
	.input-disabled{
		background-color: rgba(221, 221, 221, 1);
	}

	.input-hint {
		font-size: 20rpx;
		color: rgba(250, 79, 58, 1);
		opacity: 1;
		display: flex;
		justify-content: center;
		align-items: center;
		margin-top: 20rpx;
	}

	.input-address {
		width: 65px;
		height: 30px;
		border: 1px solid rgba(221, 221, 221, 1);
		opacity: 1;
		border-radius: 4px;
	}

	.pay-code-view {
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
		margin-left: 40rpx;
		margin-right: 40rpx;
		margin-top: 30rpx;
	}

	.pay-code-item-view {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 33.33%;
	}

	.pay-code-item {
		width: 200rpx;
		height: 380rpx;
		border: 2rpx solid rgba(255, 255, 255, 1);
		border-radius: 8rpx;
		margin-top: 20rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}

	.pay-code-item-select {
		width: 200rpx;
		height: 380rpx;
		border: 2rpx solid rgba(255, 2, 2, 1);
		border-radius: 8rpx;
		margin-top: 20rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center; 
		@include pay-code-item-select();
	}

	.pay-code-item-cover {
		width: 198rpx;
		height: 160rpx;
		border: 1rpx dashed rgba(230, 230, 230, 1);
		@include pay-code-item-select();
	}

	.pay-code-item-content {
		width: 200rpx;
		height: 220rpx;
		background: linear-gradient(137deg, rgba(250, 231, 177, 1) 0%, rgba(214, 168, 88, 1) 100%);
		/* background-color: #4CD964; */
		opacity: 1;
		border-radius: 0px 0px 4px 4px;
		display: flex;
		flex-direction: column;
		align-items: center;
		@include assess-result-share-bg();
	}

	.pay-code-title {
		height: 17px;
		font-size: 12px;
		font-family: PingFang SC;
		font-weight: 500;
		line-height: 17px;
		color: rgba(51, 51, 51, 1);
		opacity: 1;
		margin-top: 32rpx;
	}

	.pay-code-money {
		height: 24px;
		font-size: 20px;
		font-family: Impact;
		font-weight: 400;
		line-height: 24px;
		color: rgba(111, 79, 40, 1);
		opacity: 1;
		margin-top: 18rpx;
	}

	.pay-code-desc {
		height: 14px;
		font-size: 10px;
		font-family: PingFang SC;
		font-weight: 300;
		line-height: 14px;
		color: rgba(102, 102, 102, 1);
		opacity: 1;
		margin-top: 18rpx;
	}

	.pay-type-view {
		margin-top: 40rpx;
		margin-left: 40rpx;
	}

	.pay-type-item {
		width: 140px;
		height: 40px;
		border: 1px solid rgba(255, 2, 2, 1);
		opacity: 1;
		border-radius: 4px;
		display: flex;
		flex-direction: row;
		align-items: center;

		font-size: 12px;
		color: rgba(51, 51, 51, 1);
	}

	.pay-type-wx {
		width: 50rpx;
		height: 50rpx;
		margin-left: 20rpx;
		margin-right: 16rpx;
	}

	.pay-price-view {
		display: flex;
		flex-direction: row;
		flex: 1;
		margin-left: 40rpx;
		align-items: baseline;
	}
</style>
